﻿using laohan.Common.USB.DeviceNotify;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace laohan.Common.USB
{
    /// <summary>
    /// 
    /// </summary>
    public class UsbHelper
    {
        /// <summary>
        /// 热插拔消息通知
        /// </summary>
        public IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier();

        public UsbHelper()
        {
            UsbDeviceNotifier.OnDeviceNotify += UsbDeviceNotifier_OnDeviceNotify;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UsbDeviceNotifier_OnDeviceLog(object sender, LogEventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UsbDeviceNotifier_OnDeviceNotify(object sender, DeviceNotifyEventArgs e)
        {
            if (e.EventType == EventType.DeviceArrival)
            {
                //SendUIMsg(1, "usb DeviceArrival");

                new Thread(() =>
                {
                    Thread.Sleep(500);

                    InitUSB();
                }).Start();
            }
            else if (e.EventType == EventType.DeviceRemoveComplete)
            {
                //SendUIMsg(1, "usb Remove");
                CloseUSB();
            }
        }

        private USBDevice _usbDevice = null;
        private int vid = 0x2010, pid = 0x7638;
        private void InitUSB()
        {
            if (_usbDevice == null)
            {
                _usbDevice = new USBDevice(vid, pid);
                _usbDevice.OnUsbDataReceived += _usbDevice_OnUsbDataReceived;
                _usbDevice.LogEvent += _usbDevice_LogEvent;
            }
            if (_usbDevice != null && !_usbDevice.IsOpen)
            {
                _usbDevice.Open();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _usbDevice_LogEvent(object sender, LogEventArgs e)
        {
            //SendUIMsg(e.IsError ? 0 : 1, e.Msg);
        }

        private void CloseUSB()
        {
            if (_usbDevice != null && !_usbDevice.IsOpen)
            {
                _usbDevice.OnUsbDataReceived -= _usbDevice_OnUsbDataReceived;
                _usbDevice.Close();

            }
            _usbDevice = null;
        }
        private void _usbDevice_OnUsbDataReceived(byte[] data)
        {
            //数据解析
            //SendUIMsg(1, BitConverter.ToString(data));
        }
    }
}
